import { useState, useCallback } from "react";
import {
  ScrollView,
  Text,
  TouchableOpacity,
  View,
  StyleSheet,
  Image,
} from "react-native";
import { useFocusEffect } from "@react-navigation/native";
import { useAppSelector } from "app/store";
import Spinner from "react-native-loading-spinner-overlay";
import toast from "utils/toast";
import { manager } from "utils/bleManage";
import {
  WritableWithResponse,
  determineCurrentDevice,
  getStorageData,
  setStorageData,
  stringToGBKHex,
} from "utils";
import translate from "utils/translate";
type GoodsItem = {
  goodsName?: string;
  price?: string;
  unit?: string;
  id?: string;
  goodsCode?: string;
  weight?: string;
  limit?: string;
  discount_lv?: string;
  remark?: string;
  changePrice?: string;
  mode?: string;
  discount?: string;
  salePrice?: string;
};
export default ({
  navigation,
  route: { params },
}: RootStackScreenProps<"goods">) => {
  const [item, setItem] = useState<
    | (Omit<RootStackParamList["addModel"], "index"> & {
        goodsList: GoodsItem[];
      })
    | null
  >();
  const connectedDevice = useAppSelector((state) => {
    return state.app.connectedDevice;
  });
  const [loading, setLoading] = useState(false);
  const onSync = async () => {
    if (item?.goodsList.length === 0) return toast(translate("main.SyncError"));
    if (connectedDevice) {
      const modelName = item?.modelName;
      let List: string[] | undefined;
      if (modelName === "P5") {
        List = item?.goodsList.map((item, index) => {
          return (
            stringToGBKHex((index + 1).toString().padStart(4, "0")) +
            "0C" +
            stringToGBKHex(item.goodsName) +
            "0C" +
            stringToGBKHex(item.goodsCode) +
            "0C" +
            stringToGBKHex(item.price) +
            "0C" +
            stringToGBKHex(item.changePrice) +
            "0C" +
            stringToGBKHex(item.mode) +
            "0C" +
            stringToGBKHex(item.weight) +
            "0C" +
            stringToGBKHex(item.limit) +
            "0C" +
            stringToGBKHex(item.discount) +
            "0C" +
            stringToGBKHex(item.discount_lv ?? "") +
            "0C" +
            stringToGBKHex(item.remark)
          );
        });
        List = (List ?? []).map((item) =>
          item
            .replace(/0C31300C/g, "0C100C")
            .replace(/0C31310C/g, "0C110C")
            .replace(/0C31300C/g, "0C100C")
            .replace(/0C31310C/g, "0C110C")
        );
      } else {
        List = item?.goodsList.map((item, index) => {
          return (
            stringToGBKHex((index + 1).toString().padStart(4, "0")) +
            "0C" +
            stringToGBKHex(item.goodsName) +
            "0C" +
            stringToGBKHex(item.price)
          );
        });
      }
      setLoading(true);
      const services = await manager
        .discoverAllServicesAndCharacteristicsForDevice(connectedDevice)
        .then((device) => {
          return device.services();
        })
        .catch(() => {
          toast(translate("main.error"));
        });
      if (services) {
        const itemService = determineCurrentDevice(services);
        if (itemService) {
          const characteristicsList = await itemService.characteristics();
          for (let current of characteristicsList) {
            if (current.isWritableWithResponse && current.isNotifiable) {
              try {
                await WritableWithResponse(current, "AA");
                await WritableWithResponse(
                  current,
                  modelName === "P5" ? "13" : "03"
                );
                for (let p of List ?? []) {
                  const currentValue = p + "0D0A";
                  if (currentValue.length > 40) {
                    const nums = Math.ceil(currentValue.length / 40);
                    for (let p = 0; p < nums; p++) {
                      await WritableWithResponse(
                        current,
                        currentValue.substring(p * 40, (p + 1) * 40)
                      );
                    }
                  } else {
                    await WritableWithResponse(current, currentValue);
                  }
                }
                await WritableWithResponse(current, "0F");
                // getStorageData("deviceGoodsList").then(async (value) => {
                //   const deviceGoodsList = value ? JSON.parse(value) : [];
                //   const index = deviceGoodsList.findIndex((item) => {
                //     return item.deviceId == connectedDevice;
                //   });
                //   if (index !== -1) {
                //     deviceGoodsList.splice(index, 1, {
                //       deviceId: connectedDevice,
                //       goodsList: item?.goodsList ?? [],
                //     });
                //   } else {
                //     deviceGoodsList.unshift({
                //       deviceId: connectedDevice,
                //       goodsList: item?.goodsList ?? [],
                //     });
                //   }
                //   await setStorageData(
                //     "deviceGoodsList",
                //     JSON.stringify(deviceGoodsList)
                //   );
                // });
                toast(translate("main.success"));
                setLoading(false);
              } catch {
                setLoading(false);
                toast(translate("main.error"));
              }
              return;
            }
          }
        } else {
          setLoading(false);
          toast(translate("main.error"));
        }
      }
    } else {
      toast(translate("main.connectTip"));
    }
  };
  useFocusEffect(
    useCallback(() => {
      getStorageData("classList").then((value) => {
        if (value) {
          const current = JSON.parse(value)[params.index];
          const { goodsList, ...rest } = current;
          const newGoodsList =
            (goodsList || []).map((item) => {
              const { price, ...rest } = item;
              const index = [, "0.0", "0.00"].findIndex(
                (item) => item === current.point
              );
              return {
                ...rest,
                salePrice:
                  current.modelName == "P5"
                    ? index !== -1
                      ? (item.discount === "11"
                          ? ((price * item.discount_lv) / 100) * 1
                          : price * 1
                        ).toFixed(index)
                      : Math.ceil(
                          item.discount === "11"
                            ? ((price * item.discount_lv) / 100) * 1
                            : price * 1
                        ).toString()
                    : undefined,
                price:
                  index !== -1
                    ? (price * 1).toFixed(index)
                    : Math.ceil(price).toString(),
              };
            }) || [];
          setItem({
            goodsList: newGoodsList,
            ...rest,
          });
        }
      });
    }, [])
  );
  return (
    <>
      <Spinner
        visible={loading}
        textContent={translate("main.loading") + "..."}
        textStyle={{
          color: "rgba(10, 89, 247, .8)",
        }}
        color="rgba(10, 89, 247, .8)"
        cancelable
      />
      <Text
        style={{
          marginTop: 20,
          marginLeft: 20,
          fontSize: 20,
        }}
      >
        {item?.className}
      </Text>
      <ScrollView
        style={{
          flex: 1,
        }}
        contentContainerStyle={{
          alignItems: "center",
        }}
      >
        {item?.goodsList?.map((current, index) => {
          return (
            <TouchableOpacity
              key={index}
              style={{
                backgroundColor: "#fff",
                borderRadius: 10,
                width: "90%",
                marginTop: 10,
                padding: 10,
              }}
              onPress={() => {
                navigation.navigate(
                  item?.modelName === "P5" ? "addBaseGoods" : "addGoods",
                  {
                    ...current,
                    index: index + 1,
                    id: item.id,
                  }
                );
              }}
            >
              <Text>
                {(index + 1).toString().padStart(4, "0") +
                  "#" +
                  current.goodsName}
              </Text>
              <View
                style={{
                  flexDirection: "row",
                  justifyContent: "space-between",
                  marginTop: 20,
                }}
              >
                <Text style={{ color: "#8799a3" }}>
                  {translate("class.price") + ":"}
                  <Text
                    style={{
                      color: "#e54d42",
                    }}
                  >
                    {"￥" + (current.salePrice || current.price)}
                  </Text>
                </Text>
                <Text>
                  {translate("class.price") + ":"}
                  <Text
                    style={{
                      textDecorationLine: "line-through",
                    }}
                  >
                    {"￥" + current.price}
                  </Text>
                </Text>
              </View>
            </TouchableOpacity>
          );
        })}
        {item?.goodsList.length === 0 && (
          <View
            style={{
              alignItems: "center",
              marginTop: 40,
            }}
          >
            <Image
              style={{
                width: 45,
                height: 45,
                marginBottom: 20,
              }}
              source={require("assets/images/car.png")}
            ></Image>
            <Text>{translate("main.empty")}~</Text>
          </View>
        )}
      </ScrollView>
      <View
        style={{
          flexDirection: "row",
        }}
      >
        <TouchableOpacity
          onPress={() => {
            navigation.navigate(
              item?.modelName === "P5" ? "addBaseGoods" : "addGoods",
              {
                id: item?.id,
              }
            );
          }}
          style={{ ...styles.button, backgroundColor: "#4768f3" }}
        >
          <Text
            style={{
              textAlign: "center",
              color: "#fff",
            }}
          >
            {translate("class.AddGoods")}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={onSync}
          style={{ ...styles.button, backgroundColor: "#8da1f5" }}
        >
          <Text
            style={{
              textAlign: "center",
              color: "#fff",
            }}
          >
            {translate("class.Sync")}
          </Text>
        </TouchableOpacity>
      </View>
    </>
  );
};
const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: "#fff" },
  button: {
    backgroundColor: "#0A59F7",
    width: "50%",
    height: 50,
    // borderRadius: 16,
    alignItems: "center",
    justifyContent: "center",
    alignSelf: "center",
  },
});
